<!DOCTYPE html>
<html lang="zh_CN">
  <head>
	<meta charset="utf-8" />
    <script>
function checkForValidUrl(tabId, changeInfo, tab) {
	if (tab.url.match(/^http:\/\/(vipreader|www)\.qidian\.com\/bookreader\/(vip,)?\d+,\d+(,\d+)?.aspx/ig)) {
		chrome.pageAction.show(tabId);
		//chrome.tabs.executeScript(tabId, {code:'location.href="about:blank#qidian_reader=' + tab.url + '";'});
		//chrome.tabs.insertCSS(tabId, {'file' : 'css/free_reader.css'});
	/*}else if (tab.url.match(/^about:blank\?qidian_reader/ig)) {
		chrome.pageAction.show(tabId);
		//chrome.tabs.insertCSS(tabId, {'file' : 'css/free_reader.css'});
	*/
	}
};
function setIcon(name) {
	chrome.windows.getCurrent(function(topWin){
		chrome.tabs.getSelected(topWin.id, function(tab){
			chrome.pageAction.setIcon({
				'tabId' : tab.id,
				'path' : 'img/' + name + '.png'
			});
		});
	});
}
function setPopup(name) {
	chrome.windows.getCurrent(function(topWin){
		chrome.tabs.getSelected(topWin.id, function(tab){
			chrome.pageAction.setPopup({
				'tabId' : tab.id,
				'popup' : name + '.html'
			});
		});
	});
}
function config(onloadCallback) {
	var db_err = function (transaction, error){
		console.log('DB error was: '+ error.message +'(Code:'+ error.code +')');
		var fatal_error = true;
		if(fatal_error){
			return true;
		}
		return false;
	}
	var conf = {
		def : {
			font : '微软雅黑',
			size : 20,
			margin : 10,
			spacing : 20,
			text_color : '000000',
			bg_color : 'ffffff',
			auto_mark : 0,
			version : 1
		},
		font : null,
		size : null,
		margin : null,
		spacing : null,
		text_color : null,
		bg_color : null,
		auto_mark : 0,
		version : 1,
		db : openDatabase('q3_qidian_read_db', '0.1', 'Qidian Reader Database', 4096),
		onload : onloadCallback,
		getAll : function(){
			return {
				font : conf.font,
				size : conf.size,
				margin : conf.margin,
				spacing : conf.spacing,
				text_color : conf.text_color,
				bg_color : conf.bg_color,
				auto_mark : conf.auto_mark
			}
		},
		load : function() {
			var sql = 'SELECT * FROM settings;';
			conf.db.transaction(
				function (transaction){
					transaction.executeSql(sql, [], function(transaction, results) {
						if (results.rows.length == 0) {
							conf.font = conf.def.font;
							conf.size = conf.def.size;
							conf.margin = conf.def.margin;
							conf.spacing = conf.def.spacing;
							conf.text_color = conf.def.text_color;
							conf.bg_color = conf.def.bg_color;
							conf.auto_mark = conf.def.auto_mark;
							conf.version = conf.def.version;
							conf.save();
						} else {
							var row = results.rows.item(0);
							conf.font = row.font;
							conf.size = row.size;
							conf.margin = row.margin;
							conf.spacing = row.spacing;
							conf.text_color = row.text_color;
							conf.bg_color = row.bg_color;
							conf.auto_mark = row.auto_mark;
						}
						conf.onload(conf.getAll());
					}, db_err);
				}
			);
		},
		save: function() {
			var sql = 'REPLACE INTO settings values(?, ?, ?, ?, ?, ?, ?, ?);';
			conf.db.transaction(
				function (transaction){
					transaction.executeSql(sql, [conf.version, conf.font, conf.size, conf.margin, conf.spacing, conf.text_color, conf.bg_color, conf.auto_mark], null, db_err);
				}
			);
		}
	}
	
	var sql_create = 'CREATE TABLE IF NOT EXISTS settings (version INTEGER NOT NULL PRIMARY KEY, font VARCHAR(64), size INTEGER, margin INTEGER, spacing INTEGER, text_color CHAR(6), bg_color CHAR(6), auto_mark INTEGER);';
	conf.db.transaction(
		function (transaction){
			transaction.executeSql(sql_create, [], function() {conf.load()}, db_err);
			
		}
	);

	return conf;
}
var conf;

function httpGet(url, callback) {
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				callback(xhr.responseText);
			} else {
				callback(null);
			}
		}
	}
	xhr.open('GET', url, true);
	xhr.overrideMimeType('text/plain; charset=gb2312');
	
	xhr.send();
}
function getRes(file, callback) {
	console.log('get res', file);
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			callback(xhr.responseText);
		}
	}
	xhr.open("GET", chrome.extension.getURL('/res/' + file), true);
	xhr.send();
}
function template(file, bind, callback) {
	getRes(file, function(tpl) {
		var reg;
		for (key in bind) {
			reg = new RegExp('\\$\\{' + key + '\\}\\$', 'ig');
			tpl = tpl.replace(reg, bind[key]);
		}
		callback(tpl);
	});
};
/*
function httpPost(url, data, header) {
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function(data) {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				var data = xhr.responseText;
				callback(data);
			} else {
				callback(null);
			}
		}
	}
	xhr.open('GET', url, true);
	xhr.send();
}*/
var conf;
function getConf(callback) {
	if (conf) {
		callback(conf.getAll());
	} else {
		conf = config(callback);
	}
	//return conf;
}

function insertCss() {
	getConf(function(conf) {
		var bind = {
			'font' : conf.font,
			'text_color' : conf.text_color,
			'bg_color' : conf.bg_color,
		}
		bind.size = 12 + Math.floor(conf.size * 0.4);
		bind.spacing = 100 + conf.spacing * 1;
		bind.margin = 20 + conf.margin * 3;
		console.log(conf, bind);
		
		template('free_reader.css', bind, function(css){
			chrome.windows.getCurrent(function(topWin){
				chrome.tabs.getSelected(topWin.id, function(tab){
					var script = css.replace(/\r?\n/g, "\\n").replace(/[\t ]+/g, ' ').replace(/'/g, '\\\'').replace(/"/, '\\"');
					script = 'console.log($(document.body).append("<style>'+script+'</style>"));';
					console.log(script);
					chrome.tabs.executeScript(tab.id, {'code' : script});
					
				});
			});
		});
	});
}
function onRequest(req, sender, callback) {
	if (req.action == 'init') {
		getConf(callback);
	} else if (req.action == 'setIcon') {
		setIcon(req.name);
	} else if (req.action == 'getConfig') {
		callback(conf.getAll());
	} else if (req.action == 'saveConfig') {
		for (key in req.conf) {
			conf[key] = req.conf[key];
		}
		console.log(req.conf);
		conf.save();
		insertCss();
	} else if (req.action == "httpGet") {
		httpGet(req.url, callback);
	} else if (req.action == "httpPost") {
		httpPost(req.url, req.data, req.header, callback);
	} else if (req.action == "getRes") {
		getRes(req.file, callback);
	} else if (req.action == 'insertCss') {
		insertCss();
	}
}

chrome.tabs.onUpdated.addListener(checkForValidUrl);
chrome.extension.onRequest.addListener(onRequest);
    </script>
  </head>
</html>